<template>
  <view v-if="state.locale" class="bg-[#F3F4F6]">
    <view class="c-br m-[12px] bg-white">
      <van-cell-group inset>
        <van-cell title="场所名称" is-link :value="state.locale.localeName" @click="state.show = true"></van-cell>
        <van-cell title="场所位置" :value="state.locale.address"></van-cell>
        <van-cell title="创建时间" :value="state.locale.createDate"></van-cell>
        <van-cell title="开通邻里互助">
          <van-switch active-color="#07C160" inactive-color="#9C9C9E" :disabled="!state.locale.mainFlag" :checked="state.helpFlag" @change="handleHelpFlagChange" />
        </van-cell>
      </van-cell-group>
    </view>

    <view class="c-text-14 font-bold px-12px" v-if="state.showLocaleUser"> 场所成员 </view>
    <view class="c-br c-pd m-[12px] bg-white" v-if="state.showLocaleUser">
      <view class="c-text-color-grey" v-if="state.locale.mainFlag === 1">点击以下成员进入用户列表</view>

      <view class="grid grid-cols-4 gap-2 mt-[15px]">
        <view v-for="item in state.locale.list" @click="gotoUserList">
          <view class="flex m-auto justify-center items-center rounded-50% w-60px h-60px b-1 b-solid b-blue">
            <i class="i-mdi:account w-36px h-36px" style="color: blue" v-if="item.mainFlag === 1"></i>
            <i class="i-mdi:account-star w-36px h-36px" style="color: blue" v-else></i>
          </view>
          <view class="c-text-ellipsis text-align-center">{{ item.name }}</view>
        </view>
        <!-- 是主用户显示添加成员按钮 -->
        <view v-if="state.locale.mainFlag === 1">
          <view class="flex m-auto justify-center items-center rounded-50% w-60px h-60px b-1 b-dotted b-gray" @click="handleShareApp">
            <i class="i-ic:baseline-plus w-36px h-36px c-text-color-grey"></i>
          </view>
          <view class="c-text-ellipsis text-align-center">添加成员</view>
        </view>
      </view>

      <!--      <view class="flex flex-wrap justify-center items-center mt-[15px]">
        <view class="flex-1" v-for="item in state.locale.list" @click="gotoUserList">
          <view class="flex m-auto justify-center items-center rounded-50% w-60px h-60px b-1 b-solid b-blue">
            <i class="i-mdi:account w-36px h-36px" style="color: blue" v-if="item.mainFlag === 1"></i>
            <i class="i-mdi:account-star w-36px h-36px" style="color: blue" v-else></i>
          </view>
          <view class="c-text-ellipsis text-align-center">{{ item.name }}</view>
        </view>
        &lt;!&ndash; 是主用户显示添加成员按钮 &ndash;&gt;
        <view class="flex flex-1 flex-col items-center" v-if="state.locale.mainFlag === 1">
          <view class="rounded-50% w-60px h-60px b-1 b-s-dotted b-blue text-align-center align-base" @click="handleShareApp">
            <view type="default" open-type="share" class="clear-style">
              <i class="i-ic:baseline-plus w-36px h-36px c-text-color-grey"></i>
            </view>
          </view>
          <view class="user-item-name" style="color: #7c7c7c">添加成员</view>
        </view>
      </view>-->
    </view>
    <view class="c-br bg-red w-[80%] b-solid b-red b-1 p-15px mx-20px my-10px c-white text-align-center" @click="handleUnbindLocale">解绑场所</view>
    <view v-if="state.locale.mainFlag === 1" class="c-br bg-red w-[80%] b-solid b-red b-1 p-15px mx-20px my-10px c-white text-align-center" @click="gotoFastLinkman">紧急联系人</view>
  </view>

  <van-popup position="bottom" custom-style="height: 30%" round :show="state.show" @close="state.show = false">
    <view class="bg-white w-full c-br c-pd">
      <view class="mt-20px">
        <van-field :value="state.locale?.localeName" label="场所名称" placeholder="请输入场所名称" required clearable />
      </view>
      <view class="mt-36px">
        <van-button round type="primary" size="large" @click="handleUpdateLocaleName">保 存</van-button>
      </view>
    </view>
  </van-popup>
</template>

<script setup lang="ts">
import EquipRequest from '@/request/equipRequest';
import { navigate } from '@/utils/navigate';
import useModal from '@/hooks/useModal';
import useToast from '@/hooks/useToast';
import useShare from '@/hooks/useShare';

interface IState {
  show: boolean;
  showLocaleUser: boolean;
  helpFlag: boolean;
  locale?: ILocaleDetailRes;
  localeId: number;
}

const { showModal } = useModal();
const { showToast } = useToast();
const { onShareAppMessage } = useShare();
const state = reactive<IState>({ show: false, showLocaleUser: false, helpFlag: false, localeId: 0 });

onLoad((options) => {
  if (!options) return;
  state.localeId = options.id;
  getLocaleInfo(options.id);
});

const getLocaleInfo = (id: number) => {
  EquipRequest.GetLocaleDetail({ id, hasLoading: true }).then((res) => {
    if (res.data) {
      state.locale = res.data;
      state.helpFlag = res.data.helpFlag === 1;
      if ((res.data.localeType === 1 && res.data.mainFlag === 1) || res.data.localeType === 2) {
        state.showLocaleUser = true;
      }
      state.locale.address =
        (state.locale.provinceName || '') +
        (state.locale.cityName || '') +
        (state.locale.areaName || '') +
        (state.locale.streetName || '') +
        (state.locale.villageName || '') +
        (state.locale.buildName || '') +
        (state.locale.unitName || '') +
        (state.locale.floorName || '') +
        (state.locale.houseNumber || '');
    }
  });
};

const handleUpdateLocaleName = () => {
  EquipRequest.UpdateLocaleName({ localeId: state.localeId, localeNickName: state.locale!.localeName }).then((res) => {
    state.show = false;
  });
};

const handleHelpFlagChange = (e: any) => {
  EquipRequest.SetHelpFlag({ helpFlag: e.detail ? 1 : 0, localeId: state.localeId }).then((res) => {
    state.helpFlag = e.detail;
  });
};

const gotoUserList = () => {
  navigate({ url: '/subcontract/equipment/locale/detail/userList?id=' + state.localeId });
};

/**
 * 用户点击右上角分享
 * 携带参数：场所id 当前时间戳
 * 被分享页，进页面先判断十分钟时间，再判断是否已注册（根据openId），
 */
const handleShareApp = () => {
  let startTime = new Date().getTime();
  const params = {
    title: '邀您体验智慧呼叫服务', // 分享出的卡片标题
    path: '/subcontract/equipment/pages/share/index', // 他人通过卡片进入小程序的路径，可以在后面拼接URL的形式带参数
    query: 'localeId=' + state.localeId + '&startTime=' + startTime,
    imageUrl: 'https://pic.kanglailab.com/common/beeper.png', // 分享出去的图片，默认为当前页面的截图。图片路径可以是本地文件路径或者网络图片路径。支持PNG及JPG。
  };
  onShareAppMessage(params);
};

const gotoFastLinkman = () => {
  navigate({ url: '/subcontract/equipment/locale/detail/fastLink?id=' + state.localeId });
};

const handleUnbindLocale = () => {
  showModal('是否取消绑定场所？', {
    showCancel: true,
    success: (res) => {
      if (res.confirm) {
        EquipRequest.UnbindingLocale({ id: state.localeId, state: -1 }).then((res) => {
          showToast('解绑成功', 'success');
          navigate({ type: 'navigateBack', url: '' });
        });
      }
    },
  });
};
</script>
